<!-- 河道图 -->
<template>
  <div>
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="selectATit"
          :param="param"
          :tname="tname"
          :leftTreeParentId="0"
          :searchWord="searchWord"
          @getChartData="getChartData"
        ></ChooseScreen>
      </template>
      <template slot="chart">
        <ChartG
          v-if="datatype !== -1"
          :chartId="chartId"
          :chartData="chartData"
          :caty="caty"
          @chartDom="chartDom"
        />
        <div v-else class="chart-loading-box">
          <loading1 :emptyText="emptyText" />
        </div>
      </template>
      <template slot="type">
        <!-- <i class="icon el-icon-download" @click="exportData">导出数据</i> -->
        <i class="icon el-icon-download" @click="downloadImg">保存图片</i>
      </template>
    </c-slot>

    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit">
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
        >
          <p>{{ index + 1 }}</p>
          <p v-for="(ite, j) in item" :key="j">{{ ite }}</p>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartG from "../charts/ChartG";
import {
  refactor,
  getYear,
  downloadChartImg,
  transCNCountry
} from "@/utils/utils";
import base64 from "@/utils/base64.js";
import ChooseScreen from "./chooseScreen.vue";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object
    },
    dcData: {
      type: Object
    }
  },
  components: {
    CSlot,
    ChartG,
    ChooseScreen
  },
  data() {
    return {
      loading: true,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      charttype: -1, // 图表类型
      selectATit: "", // 筛选条件A，动态
      timeType: "", // 设置时间筛选类型
      chartId: "", // 图表id名称
      datatype: -1, // 图表数据类型
      chartData: [],
      caty: [],
      chartType: "line",
      dom: {},
      tableData: {
        tit: [],
        content: []
      },
      yearArr: [],
      emptyText: "数据加载中...",
      dbid: "",
      timeType: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: ""
    };
  },
  computed: {
    ...mapState(["searchWord"])
  },
  watch: {
    dcData() {
      this.dbid = this.$route.query.type || this.$route.query.dbid;
      this.init();
    },
  },
  mounted() {
    this.dbid = String(this.$route.query.type);
    // this.init();
  },
  methods: {
    init() {
      this.tname = this.chartTempl.tname;
      this.param = this.chartTempl.tdata.param;
      this.charttype = this.chartTempl.tdata.charttype;
      this.chartId = "chart" + this.chartTempl.id;
      this.timeType = this.chartTempl.tdata.datefield;
      this.datefieldformat = this.chartTempl.tdata.datefieldformat;
      this.datefieldformatTxt = this.datefieldformat == 1 ? "-01-01" : "";
      this.chartData = [];
      this.dcData?.chartData?.map(item => {
        item.childs &&
          item.childs.map(it => {
            let arr = [];
            arr[0] = it.key_as_string || it.key;
            arr[1] = it.doc_count;
            arr[2] = item.key;
            this.chartData.push(arr);
          });
          this.caty.push(item.key)
      });
      this.loading = false;

      this.datatype = this.chartTempl.tdata.datatype;
    },
    getChartData(Params) {
      this.loading = true;
      let ths = this;
      if (this.cancel !== null) {
        this.cancel();
      }
      let sq = `${this.timeType}>=${Params.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${Params.endYear}${this.datefieldformatTxt}`;
      if (this.searchWord !== "") {
        sq = `${this.searchWord} AND ` + sq;
      }
      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = [];
      this.tableData = {
        tit: [],
        content: []
      };
      this.chartTempl.tdata.param.aggs[0]["size"] = Params.size;
      let params = {
        aggs: this.chartTempl.tdata.param.aggs,
        dbid: this.dbid,
        eSearch: sq,
        ipi: 1,
        ips: 0,
        rSearch: "",
        smartSearch: "",
        sort: []
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      this.$post(this.$Url.search.commonSearch, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
          ths.loading = false;
        })
      })
        .then(res => {
          this.$store.commit("setTotalTxt", res.data.total);
          res.data.chartData.map(item => {
            item.childs &&
              item.childs.map(it => {
                let arr = [];
                arr[0] = it.key_as_string || it.key;
                arr[1] = it.doc_count;
                arr[2] = item.key;
                this.chartData.push(arr);
              });
          });
          this.loading = false;
        })
        .catch(err => {
          this.emptyText = "暂无数据";
          this.loading = false;
        });
    },
    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    downloadImg() {
      downloadChartImg(this.dom);
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws = XLSX.utils.aoa_to_sheet(
        aoa
      ); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    }
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      this.loading = false;
      this.cancel();
    }
  }
};
</script>

<style lang="scss"></style>
